<script setup>
import { computed } from 'vue';
const emit = defineEmits(['update:modelValue', 'change', 'input']);
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  size: {
    type: [Number, String],
    default: 16
  },
  activeColor: {
    type: String,
    default: '#2979ff'
  },
  inactiveColor: {
    type: String,
    default: '#c5c3c3'
  },
  modelValue: {
    type: Boolean,
    default: false
  },
  nodeColor: {
    // 新增 prop
    type: String,
    default: '#fff'
  }
});

// 计算开关的样式
const switchStyle = computed(() => ({
  fontSize: getSizeInPx(props.size),
  backgroundColor: getBackgroundColor()
}));

// 计算开关的类名
const switchClasses = computed(() => ({
  'u-switch--on': props.modelValue,
  'u-switch--disabled': props.disabled
}));

function handleClick() {
  if (!props.disabled && !props.loading) {
    try {
      const newValue = !props.modelValue;
      emit('update:modelValue', newValue);
      emit('change', newValue);
      emit('input', newValue);
    } catch (error) {
      console.error('Error updating switch value:', error);
    }
  }
}

function getSizeInPx(size) {
  return typeof size === 'number' ? `${size}px` : size;
}

function getBackgroundColor() {
  return props.modelValue ? props.activeColor : props.inactiveColor;
}
</script>

<template>
  <div class="u-switch" :class="switchClasses" @click="handleClick" :style="switchStyle">
    <div class="u-switch__node"></div>
  </div>
</template>

<style lang="less" scoped>
.u-switch {
  position: relative;
  display: inline-block;
  box-sizing: initial;
  width: 50px;
  height: 25px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 20px;
  transition: background-color 0.3s;
}

.u-switch__node {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  width: 25px;
  height: 25px;
  border-radius: 100%;
  z-index: 1;
  background-color: v-bind('props.nodeColor'); // 使用 v-bind 绑定 nodeColor
  box-shadow:
    0 3px 1px 0 rgba(0, 0, 0, 0.05),
    0 2px 2px 0 rgba(0, 0, 0, 0.1),
    0 3px 3px 0 rgba(0, 0, 0, 0.05);
  transition: transform 0.3s cubic-bezier(0.3, 1.05, 0.4, 1.05);
}

.u-switch--on .u-switch__node {
  transform: translateX(25px); /* 调整为固定值 */
  opacity: 1;
}

.u-switch--disabled {
  opacity: 0.35;
}
</style>
